package com.quancheng.component.requestformat.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zhouchaoqun
 * @email zhouchaoqun@quancheng-ec.com
 * @created 2018/2/2 下午6:48
 */
public class JsonShapingUtil {
    private final static String UNDERSCORE_CASE_REGX = "\"((\\w+)_([a-z])(\\w*))\":";
    private final static String CAMEL_CASE_REGX = "\"((\\w+)([A-Z])(\\w*))\":";

    /**
     * 转驼峰
     * @param json
     * @return
     */
    public static String toCamelCase(String json)  {

        Pattern pattern = Pattern.compile(UNDERSCORE_CASE_REGX);
        Matcher matcher = pattern.matcher(json);
        matcher.reset();
        boolean result = matcher.find();
        if (result) {
            StringBuffer sb = new StringBuffer();
            do {
                String replacement = "\"" + matcher.group(2)+matcher.group(3).toUpperCase()+ matcher.group(4)+"\":";
                matcher.appendReplacement(sb, replacement);
                result = matcher.find();
            } while (result);
            matcher.appendTail(sb);
            return toCamelCase(sb.toString());
        }
        return json;
    }

    /**
     * 转下划线
     * @param json
     * @return
     */
    public static String toUnderScoreCase(String json) {
        Pattern pattern = Pattern.compile(CAMEL_CASE_REGX);
        Matcher matcher = pattern.matcher(json);
        matcher.reset();
        boolean result = matcher.find();
        if (result) {
            StringBuffer sb = new StringBuffer();
            do {
                String replacement = "\"" + matcher.group(2)+"_"+matcher.group(3).toLowerCase()+ matcher.group(4)+"\":";
                matcher.appendReplacement(sb, replacement);
                result = matcher.find();
            } while (result);
            matcher.appendTail(sb);
            return toUnderScoreCase(sb.toString());
        }
        return json;
    }
}
